<?php
/**
 * A very light framework built on webappkit kits structure
 *
 *
 * This file is part of Webappkit, a packages system for PHP web apps
 * @link http://webappkit.net
 * @package webappkit
 * @subpackage engine
 * @author J.Ducastel <nospam0@ducastel.name>
 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
 */
class WakEngineTool extends WakTool {

    function toolFactory($kit,$cfg) {
        return new WakEngineTool($kit,$cfg);
    }

    /**
	 * Serves http requests.
	 * Splits request URI into segments
	 * , and searches how to serve next path segment :
	 * - explicit aliases
	 * - self methods
	 * @access public
	 * @param UrlBean $uri
	 * @return bool
	 */
    function run($uri=null) {
        // echo "<p>running engine tool</p>";
        // doing pre-controller stuff, like authentication etc
        $this->setUp();
        // searching and running appropriate controller, or throwing 404
		if (!$this->runMethodController($uri)) {
			return false;
		}
        // doing post-controller stuff (like rendering etc)
        $this->tearDown();
        return true;
    }

    /**
     * doing pre-controller stuff like authentication etc
     */
    function setUp() {


    }

    /**
     * doing post-controller stuff like rendreing etc
     * @access public
     * @return bool
     */
    function tearDown() {
		// exit;
    }

    /**
     * search for an own method controller to serve current node
     * @access protected
	 * @param UrlBean $uri uri to serve
     * @return bool
     */
    function runMethodController($uri) {
        // what is the current uri path segment (=node) to serve ?
        // getting remaining nodes
        $nodes=$uri->splitPath();
        $method=array_shift($nodes);
        if (!$method)
            $method='index';
        // echo $method;
        if (!method_exists($this,$method))
            return false;
        switch (count($nodes)) {
            case 0:
                return $this->$method();
            case 1:
                return $this->$method($nodes[0]);
            case 2:
                return $this->$method($nodes[0],$nodes[1]);
            case 3:
                return $this->$method($nodes[0],$nodes[1],$nodes[2]);
            case 4:
                return $this->$method($nodes[0],$nodes[1],$nodes[2],$nodes[3]);
            default:
                return false;
        }
    }
}
?>
